package gongshw.bank.service;

import gongshw.bank.factory.DaoFactory;
import gongshw.bank.model.User;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserService implements UserServiceInterface
{
	
	private static UserService userService=new UserService();
	
	private UserService()
	{
		
	}
	
	public static UserService getInstance()
	{
		return userService;
	}
	
	public User validateUser(String userid)
	{
		User user=DaoFactory.getUserDao().find("userid",userid);
		if(user==null)
		{
			return null;
		}
		
		return user;
	}
	
	
	public Integer validateNumber(String number)
	{
		Integer num=null;
		try
		{
			num=Integer.valueOf(number);
		}
		catch(Exception e)
		{
			return null;
		}
		
		if(num.intValue()<=0)
		{
			return null;
		}
		
		return num;
	}
	
	public void sentErrorMessage(String message,HttpServletRequest req,HttpServletResponse resp) 
					throws ServletException,IOException
	{
		req.setAttribute("message",message);
		RequestDispatcher dispater=req.getRequestDispatcher(resp.encodeURL("/error/error.jsp"));
		dispater.forward(req,resp);
	}
	

	public void sentMessage(String message,HttpServletRequest req,HttpServletResponse resp) 
					throws ServletException,IOException
	{
		req.setAttribute("message",message);
		RequestDispatcher dispater=req.getRequestDispatcher(resp.encodeURL("/message/message.jsp"));
		dispater.forward(req,resp);
	}
	

	public void forwardPage(String page,HttpServletRequest req,HttpServletResponse resp) 
					throws ServletException,IOException
	{
		RequestDispatcher dispater=req.getRequestDispatcher(resp.encodeURL(page));
		dispater.forward(req,resp);
	}

}
